/**
 * 网络请求工具
 * Created by lifetime on 2018/1/25.
 */
import { HttpClient, HttpParams,HttpHeaders } from '@angular/common/http';
import { Injectable } from '@angular/core';
import {Observable} from "rxjs/Observable";
import 'rxjs/add/operator/map';
import 'rxjs/rx';

import { ApiHost } from './Constants';

@Injectable()
export class HttpUtil{

  constructor (public http: HttpClient){

  }

  /**
   *
   * @param url 前面要带上 “/”
   * @param params get请求的参数
   * @returns {Promise<R>|Observable}
   */
  get(url:string,params:HttpParams):Observable<any>{
    return (<any>this.http.get(ApiHost + url,{params})).catch( error => {
      return <Observable<any>>(<any>Observable).of({state:false,msg:"网络异常"});
    });
  }

  /**
   *
   * @param url 前面要带上 “/”
   * @param params post请求的参数
   * @returns {Promise<R>|Observable}
   */
  post(url:string,params:HttpParams):Observable<any>{
    return (<any>this.http.post(ApiHost + url,params,{
      headers:new HttpHeaders({
        'Content-Type':'application/x-www-form-urlencoded; charset=utf-8'
      })
    })).catch( error => {
      return <Observable<any>>(<any>Observable).of({state:false,msg:"网络异常"});
    });
  }

/**
   *
   * @param url 前面要带上 “/”
   * @param params post请求的参数
   * @returns {Promise<R>|Observable}
   */
  json(url:string,params:HttpParams):Observable<any>{
    return (<any>this.http.post(ApiHost + url,params,{
      headers:new HttpHeaders({
        'Content-Type':'application/json;charset=UTF-8'
      })
    })).catch( error => {
      return <Observable<any>>(<any>Observable).of({state:false,msg:"网络异常"});
    });
  }


}
